//
//  KnowledgeModel.m
//  DeepBreathing
//
//  Created by rimi on 15/12/17.
//  Copyright © 2015年 rimi. All rights reserved.
//

#import "KnowledgeModel.h"

#import "NetworkManger+NetWorkKingManger.h"

@implementation KnowledgeModel
{
    NSInteger _page;
}

-(void)getDataWithPage:(NSInteger)page shouldAddPage:(BOOL)flag{
    
    [NetworkManger knowledeListWithPage:page successHander:^(id responseObject) {
        self.knowledge = responseObject;
        
        if (flag && [self.knowledge count] != 0) {
            _page++;
            
        }
        //归档
        [NSKeyedArchiver archiveRootObject:self toFile:[KnowledgeModel archiveePath]];
    } failureHander:^(NSError *error) {
        
        self.knowledge = [NSNull null];
        
    }];
    
}

+(NSString *)archiveePath{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *basePath = paths.firstObject;
    
    return [basePath stringByAppendingString:@"knowledge.dat"];
    
    
    
}

-(instancetype)init{
    self = [super init];
    id obj1 = [NSKeyedUnarchiver unarchiveObjectWithFile:[KnowledgeModel archiveePath]];//解挡
    
    //如果本地没有数据就建立一个空对象
    
    if (obj1) {
        //如果本地有对象就把它赋给SELF
        self = obj1;
    }
    //否则，就应该返回刚才初始化的那个空对象
    //返回self
    
    return self;
    
    
    
}


-(void)getData{
    [self getDataWithPage:1 shouldAddPage:NO];
}
-(void)getMoreData{
    [self getDataWithPage:_page shouldAddPage:YES];
}

#pragma mark -- coding
//归档
-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.knowledge forKey:@"knowledge"];
}
-(id)initWithCoder:(NSCoder *)aDecoder{
    
    self = [super init];
    
    self.knowledge = [aDecoder decodeObjectForKey:@"knowledge"];
    
    return self;
    
}
@end
